<template>
	<view class="blood_oxygen">
		<!-- 血氧 -->
		<view class="card blood" :class="{ noDay: selectType !== 'day' }">
			<view class="head">
				<image class="w-92rpx" src="@/static/ring/chart/blood.png" mode="widthFix"></image>
				<view class="title">血氧</view>
				<uni-icons type="info-filled" class="ml-10rpx" size="20" color="#666666" @click="openTip"></uni-icons>
				<view class="value">{{ blood.averageNum }}<text>%</text></view>
			</view>
			<view class="chart">
				<view v-if="notDataOrLoading" class="noData_loading_mask">
					{{ !blood.loading ? "暂无数据" : "加载中..." }}
				</view>
				<l-echart ref="chartRef"></l-echart>
			</view>
			<view v-if="selectType === 'day' && blood.averageNum" class="range">
				<view class="des">
					<view class="desTop">
						<view class="dot"></view>
						<view class="titleTime text-#AFAFAF"> 范围 </view>
					</view>
					<view class="value">{{ blood.min }} - {{ blood.max }} <text class="unit">%</text></view>
				</view>
			</view>
		</view>

		<!-- info -->
		<view class="info" v-if="blood.healthText && blood.averageNum">
			<view class="info-title">
				<image src="@/static/ring/chart/blood.png" class="w-60rpx mr-8rpx" mode="widthFix" />
				血氧饱和度
			</view>
			<view class="info-content">
				<text>{{ blood.healthText }}</text>
			</view>
		</view>
	</view>
</template>

<script>
import dayjs from "dayjs";
import * as echarts from "echarts";

import bImage from '@/static/ring/chart/blood.png'

import { queryMyBloodOxInfoByDay, queryMyBloodOxInfoByWeek, queryMyBloodOxInfoByMonth } from "@/api/ring/chart.js";

const tip_zh = `
血氧饱和度（SpO2）表示血液中氧气的饱和程度，通常在95%-100%之间。少数健康个体可能低于95%，但若血氧饱和度低于90%请注意观察，必要请及时就医。

请在静息状态下将设备的传感器凸点紧贴指腹，以确保准确读数。

*运动或在身处高原地区时，血氧浓度数据可能与实际有一定偏差。

注：本设备提供的检测数据仅用于日常健康管理辅助参考，不可替代专业医疗诊断。
`;

const _options = {
	grid: {
		left: "0",
		right: "15",
		top: "10",
		bottom: "2",
		containLabel: true,
	},
	xAxis: [
		{
			show: true,
			type: "category",
			boundaryGap: false,
			axisTick: {
				show: false,
			},
			axisLine: {
				//坐标轴轴线相关设置。数学上的x轴
				show: true,
				lineStyle: {
					color: "rgba(141, 141, 141, 0.3)",
				},
			},
			axisLabel: {
				//坐标轴刻度标签的相关设置
				color: "rgba(0, 0, 0, 0.5)",
			},
		},
	],
	yAxis: [
		{
			type: "value",
			min: 0,
			splitLine: {
				show: true,
				lineStyle: {
					type: "dashed",
					color: "rgba(141, 141, 141, 0.3)",
				},
			},
			axisLabel: {
				//坐标轴刻度标签的相关设置
				color: "rgba(0, 0, 0, 0.5)",
			},
		},
	],
};

export default {
	props: {
		selectDateInfo: Object,
	},
	data() {
		return {
			selectType: "day",
			blood: {
				showTip: false,
				tipText: tip_zh,
				max: 0,
				min: 0,
				averageNum: 0,
				chartData: [],
				chartRef: null,
				chart: null,
				healthText: "",
				healthModelValue: 0,
				loading: false,
				empty: false,
			},
		};
	},

	computed: {
		notDataOrLoading() {
			const data = this.blood.chartData;
			return !data || !Array.isArray(data) || !data.length;
		},

		optionsByDay() {
			return {
				..._options,
				series: [
					{
						type: "bar",
						barWidth: 6,
						itemStyle: {
							opacity: 1,
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
								{
									offset: 0,
									color: "rgba(247, 61, 61, 1)",
								},
								{
									offset: 1,
									color: "rgba(244, 103, 103, 0.3)",
								},
							]),
							borderRadius: 10,
						},
						data: this.blood.chartData,
					},
				],
			};
		},
		optionsByOther() {
			return {
				..._options,
				series: [
					{
						name: "血氧",
						type: "line",
						smooth: false,
						lineStyle: {
							width: 1.5,
							color: "rgba(247, 61, 61, 1)",
						},
						areaStyle: {
							opacity: 0,
						},
						showSymbol: true,
						symbol: "circle",
						itemStyle: {
							color: "rgba(247, 61, 61, 1)",
						},
						data: this.blood.chartData,
					},
				],
			};
		},
	},

	watch: {
		selectDateInfo: {
			handler(nv) {
				this.selectType = nv.type;
				this.bloodOxygenOnChange(nv);
			},
			immediately: true,
			deep: true,
		},

		optionsByDay: {
			handler(nv) {
				if (this.selectType === "day") {
					if (this.blood.chart) {
						this.blood.chart.setOption(nv);
					}
				}
			},
			deep: true,
		},

		optionsByOther: {
			handler(nv) {
				if (this.selectType !== "day") {
					if (this.blood.chart) {
						this.blood.chart.setOption(nv);
					}
				}
			},
			deep: true,
		},
	},

	async mounted() {
		if (!this.blood.chartRef) {
			this.blood.chartRef = this.$refs.chartRef;
		}
		if (this.blood.chartRef) {
			this.blood.chart = await this.blood.chartRef.init(echarts);
		}
	},

	methods: {
		async bloodOxygenOnChange(data) {
			const { type, startTime, endTime } = data;
			this.blood.max = 0;
			this.blood.min = 0;
			this.blood.averageNum = 0;
			this.blood.healthText = "";
			this.blood.healthModelValue = 0;
			this.blood.chartData = [];
			this.blood.loading = true;
			this.resetData();

			const offsetMinutes = new Date().getTimezoneOffset();

			const params =
				type == "day"
					? { dateStr: startTime, offsetMinutes }
					: type === "week"
					? { dateBeginStr: startTime, dateEndStr: endTime, offsetMinutes }
					: { dateBeginStr: startTime, dateEndStr: endTime, offsetMinutes };
			console.log("params", params);

			const requestMethod = type == "day" ? queryMyBloodOxInfoByDay : type == "week" ? queryMyBloodOxInfoByWeek : queryMyBloodOxInfoByMonth;

			try {
				const { data } = await requestMethod(params);

				console.log("bloodOxygenOnChange", data);

				this.blood.loading = false;
				if (this.blood.chart) {
					this.blood.chart.clear();
				}
				if (!data) {
					this.resetData();
					return;
				}

				this.blood.max = parseInt(data.max || 0);
				this.blood.min = parseInt(data.min || 0);
				this.blood.averageNum = parseInt(data.average || 0);
				this.blood.healthText = data?.bloodOxModel?.config?.modelZh;
				this.blood.healthModelValue = parseInt(data?.bloodOxModel?.value || 0);
				if (!data.rates) return;
				const dealWith = type == "day" ? this.bloodGetFullByDay : this.bloodGetFullByOther;
				dealWith(data.rates || []);
			} catch (error) {
				console.log("heartRateOnChange error", error);
				this.resetData();
			}
		},

		bloodGetFullByDay(data) {
			let res = [];
			for (let i = 0; i < 24; i++) {
				const has = data.findIndex((item) => Number(item.time) === i);
				if (has != -1) {
					res.push([i.toString() + ":00", data[i].value || null]);
				} else {
					res.push([i.toString() + ":00", null]);
				}
			}
			res.sort((a, b) => Number(a[0]) - Number(b[0]));
			this.blood.chartData = res;
		},

		bloodGetFullByOther(data) {
			const cycleCount = this.selectType == "week" ? 7 : data.length;
			let res = [];
			for (let i = 0; i < cycleCount; i++) {
				res.push([dayjs(data[i].date).format("MM.DD"), data[i].value || null]);
			}
			this.blood.chartData = res;
		},

		async resetData() {
			this.blood.chartData = [];
			this.blood.averageNum = 0;
		},

		openTip() {
			const tips = {
				tip: tip_zh,
				icon: bImage,
				title: "血氧",
			};

			this.$emit("tips", tips);
		},
	},
};
</script>

<style lang="scss" scoped>
.blood_oxygen {
	width: 100%;
	height: max-content;

	.w-92rpx {
		width: 92rpx;
	}

	.w-60rpx {
		width: 60rpx;
	}

	.w-70rpx {
		width: 70rpx;
	}

	.w-40rpx {
		width: 40rpx;
	}

	.w-30rpx {
		width: 30rpx;
	}

	.mr-8rpx {
		margin-right: 8rpx;
	}

	.text-#AFAFAF {
		color: #afafaf;
	}

	.card {
		width: 100%;

		background-color: rgba($color: white, $alpha: 0.5);
		backdrop-filter: blur(20rpx);
		border-radius: 50rpx;
		height: 740rpx;

		padding: 40rpx;

		display: flex;
		flex-direction: column;
		justify-content: space-between;

		.head {
			width: 100%;
			height: 70rpx;
			display: flex;
			align-items: center;
			justify-content: flex-start;

			.title {
				font-size: 32rpx;
				font-weight: 600;
				text-align: left;
				margin-left: 6cap;
				margin-right: 12rpx;
			}

			.value {
				margin-left: auto;
				font-weight: 500;
				font-size: 64rpx;

				text {
					font-size: 24rpx;
				}
			}
		}

		.chart {
			width: 100%;
			height: 400rpx;
			position: relative;

			.noData_loading_mask {
				position: absolute;
				left: 0;
				top: 0;
				width: 100%;
				height: 100%;
				background-color: #e3f1fb;
				display: flex;
				justify-content: center;
				align-items: center;
				text-align: center;
				line-height: 150px;
				font-size: 28rpx;
				color: rgba(45, 153, 255, 1);
			}
			// background-color: #e5404f;
		}

		.range {
			display: flex;
			padding: 20rpx 52rpx 0 40rpx;
			font-weight: 500;

			.des {
				flex: 1;
				color: black;
				font-size: 32rpx;

				.desTop {
					display: flex;
					align-items: center;
					margin-bottom: 4rpx;
					white-space: nowrap;

					.titleTime {
						font-size: 28rpx;
						color: black;
						margin-left: 20rpx;
					}

					.dot {
						background: #e5404f;
						border-radius: 50%;
						width: 10rpx;
						height: 10rpx;
					}
				}

				.value {
					padding-left: 30rpx;

					.unit {
						font-size: 24rpx;
						margin-left: 8rpx;
					}
				}
			}
		}

		& + .card {
			margin-top: 40rpx;
			height: 730rpx;
		}

		&.noDay.blood {
			height: 640rpx;
		}
	}

	.info {
		color: black;
		padding: 40rpx;

		.info-title {
			height: 60rpx;
			display: flex;
			align-items: center;
			font-family: PingFang HK;
			font-size: 36rpx;
			font-weight: 600;
			line-height: 50px;
			text-align: left;
			padding: 40rpx 0;

			.value {
				margin-left: auto;
			}
		}

		.info-content {
			font-family: PingFang SC;
			font-size: 28rpx;
			font-weight: 300;
			line-height: 40rpx;
			text-align: left;
		}
	}
}
</style>
